package com.frx.leetcode.one;

import java.util.Stack;

/** 第20题 括号匹配问题
 * https://leetcode-cn.com/problems/valid-parentheses/
 */
public class VaildParenttheses {

    public static void main(String[] args){
        String str = "";
        System.out.println(isValid(str));
        System.out.println(solution(str));
    }

    public static boolean isValid(String s){
        if (s.equals("") || s == null){
            return true;
        }
        String[] arr = s.split("");
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < arr.length; i++){
            if (arr[i].equals("(") || arr[i].equals("[") || arr[i].equals("{")){
                stack.push(arr[i]);
            } else {
                String str = arr[i];
                if (stack.empty()){
                    return false;
                }
                String s1 = stack.pop();
                if ((s1.equals("(") && str.equals(")")) ||
                        (s1.equals("[") && str.equals("]")) ||
                        (s1.equals("{") && str.equals("}"))){
                    continue;
                } else {
                    return false;
                }
            }
        }

        return stack.empty();
    }

    public static boolean solution(String s){
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            switch (c){
                case '[' :
                case '(' :
                case '{' :
                    stack.push(c);
                    break;
                case ')' :
                    if (!stack.empty()){
                        if (stack.peek() == '('){
                            stack.pop();
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                    break;
                case ']' :
                    if (!stack.empty()){
                        if (stack.peek() == '['){
                            stack.pop();
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
                    break;
                case '}' :
                    if (!stack.empty()){
                        if (stack.peek() == '{'){
                            stack.pop();
                        } else {
                            return false;
                        }
                    } else {
                        return false;
                    }
            }

        }
        return stack.empty();
    }
}
